import oss2
from mylogger import Mylogger
log = Mylogger()


class OssUtil:
    """
        初始化
    """
    def __init__(self, bucketName, accessKeyId, accessKeySecret):
        self.bucket_name = bucketName    
        self.access_key_id = accessKeyId 
        self.access_key_secret = accessKeySecret 
          
    # 检测文件是否存在并上传
    def upload_file_to_oss(self, file_path):
        auth = oss2.Auth(self.access_key_id, self.access_key_secret)
        bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', self.bucket_name)

        # 检查文件是否存在于OSS
        if not bucket.object_exists(file_path):
            # 上传文件到OSS
            with open(file_path, 'rb') as file:
                bucket.put_object(file_path, file)

            log.printLog( "文件上传成功！")
        else:
            log.printLog("文件已存在于OSS，无需上传。")

    # 从OSS下载文件

    def download_file_from_oss(self, file_name):
        auth = oss2.Auth(self.access_key_id, self.access_key_secret)
        bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', self.bucket_name)

        # 下载文件
        local_file_path = './' + file_name  # 下载文件保存到本地的路径
        bucket.get_object_to_file(file_name, local_file_path)
        log.printLog( "文件下载成功！")
